package com.carbohydrate42.kotlin_compose_demo.compose

import android.speech.tts.TextToSpeech
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp


@Composable
@Preview(showBackground = false, name = "Text to speech", showSystemUi = true)
fun TryTextToSpeech() {

    val context = LocalContext.current

    var isInitialized by remember {
        mutableStateOf(false)
    }

    var speakText by remember {
        mutableStateOf("")
    }

    // 文本转语音
    val textToSpeech = TextToSpeech(context) {
        isInitialized = true
    }.apply {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        setPitch(1.0f)
        // 设置语速
        setSpeechRate(0.8f)
    }

    if (isInitialized) {
        Row {
            OutlinedTextField(
                modifier = Modifier.width(200.dp),
                value = speakText,
                onValueChange = { speakText = it },
                label = { Text("Speak text") },
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
            )
            Button(onClick = {
                // 打断
                textToSpeech.stop();
                // 读文本
                textToSpeech.speak(
                    speakText,
                    TextToSpeech.QUEUE_FLUSH,
                    null,
                    null
                )
            }) {
                Text(text = "say this")
            }
        }
    } else {
        CircularProgressIndicator()
        Text(text = "Initializing...")
    }
}